package com.yuanqi.java.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.java.entity.Product;
import com.yuanqi.java.entity.CommodityCategory;
import com.yuanqi.java.service.IProductService;
import com.yuanqi.java.mapper.CommodityCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品SPU 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-08-26
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;
    @Autowired
    private CommodityCategoryMapper categoryMapper;

    // 简易产品分页查询，支持按名称/编码/条码模糊搜索、按供应商编码筛选、只看未关联产品
    @GetMapping
    public IPage<Product> page(@RequestParam(defaultValue = "1") long pageNum,
                               @RequestParam(defaultValue = "10") long pageSize,
                               @RequestParam(required = false) String keyword,
                               @RequestParam(required = false) String supplierCode,
                               @RequestParam(required = false, defaultValue = "false") boolean unboundOnly) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Product> qw = Wrappers.lambdaQuery(Product.class);
        if (StringUtils.hasText(keyword)) {
            qw.like(Product::getProductName, keyword)
              .or().like(Product::getSpuCode, keyword)
              .or().like(Product::getBarCode, keyword);
        }
        if (StringUtils.hasText(supplierCode)) {
            qw.eq(Product::getSupplierCode, supplierCode);
        } else if (unboundOnly) {
            qw.isNull(Product::getSupplierCode);
        }
        qw.orderByDesc(Product::getId);
        IPage<Product> result = productService.page(page, qw);
        // 填充分类名称
        List<Product> items = result.getRecords();
        Set<Long> ids = items.stream().map(Product::getCategoryId).filter(v -> v != null && v > 0).collect(Collectors.toSet());
        Set<String> codes = items.stream().map(Product::getCategoryCode).filter(c -> c != null && !c.isEmpty()).collect(Collectors.toSet());
        if (!ids.isEmpty() || !codes.isEmpty()) {
            List<CommodityCategory> cats;
            if (!ids.isEmpty()) {
                cats = categoryMapper.selectList(Wrappers.<CommodityCategory>lambdaQuery().in(CommodityCategory::getId, ids));
            } else {
                cats = categoryMapper.selectList(Wrappers.<CommodityCategory>lambdaQuery().in(CommodityCategory::getCategoryCode, codes));
            }
            Map<Long, String> idToName = cats.stream().collect(Collectors.toMap(CommodityCategory::getId, CommodityCategory::getCategoryName, (a,b)->a));
            Map<String, String> codeToName = cats.stream().collect(Collectors.toMap(CommodityCategory::getCategoryCode, CommodityCategory::getCategoryName, (a,b)->a));
            items.forEach(p -> {
                if (p.getCategoryId() != null && idToName.containsKey(p.getCategoryId())) {
                    p.setCategoryName(idToName.get(p.getCategoryId()));
                } else if (p.getCategoryCode() != null) {
                    p.setCategoryName(codeToName.get(p.getCategoryCode()));
                }
            });
        }
        return result;
    }
}
